package com.ffcs.cn.action.desktopcontrol.smDialogProgress;

import com.supermap.desktop.controls.ui.controls.progress.FormProgressCancelledListener;
import com.supermap.desktop.controls.ui.controls.progress.SmDialogProgress;
import com.supermap.desktop.core.Application;
import com.supermap.desktop.core.Interface.IBaseItem;
import com.supermap.desktop.core.implement.CtrlAction;
import com.supermap.desktop.core.progress.Interface.UpdateProgressCallable;

import java.util.concurrent.CancellationException;
import java.util.concurrent.TimeUnit;

/**
 * 单进度条
  *
 */
public class CtrlActionSmDialogProgress extends CtrlAction {

	public CtrlActionSmDialogProgress(IBaseItem caller) {
		super(caller);
	}

	@Override
	protected void run() {
		SmDialogProgress progress = new SmDialogProgress("单进度条");
		//添加任务取消监听器
		progress.addFormProgressCancelledListener(new FormProgressCancelledListener() {
			@Override
			public void formProgressCancelled() {
				Application.getActiveApplication().getOutput().output("任务已取消。");
			}
		});
		//执行任务
		progress.doWork(new UpdateProgressCallable() {
			@Override
			public Boolean call() throws Exception {
				//模拟执行任务
				int total = 100;
				int start = 1;
				int timeOut = 500;
				try {
					for (int i = start; i <= total; i++) {
						TimeUnit.MILLISECONDS.sleep(timeOut);
						int percent = (int)(i * 1.0 / total * 100);
						String remainTime = TimeUnit.MILLISECONDS.toSeconds((total-i) * timeOut) + " 秒";
						//更新进度条进度
						progress.updateProgress(percent,remainTime,"正在执行"+i+"/"+total);
					}
					return true;
				}catch (CancellationException e){
					//任务被取消，返回 false
					return false;
				}
			}
		});
	}
}
